import openpyxl
import copy
import threading
from pubsub import pub
import wx

from ParseFormula import ParseFormula
from ParseGauge import ParseGauge

class ParseXls:

    def __init__(self, path, mainframe, expath):
        self.Book = openpyxl.load_workbook(path)
        self.MainFrame = mainframe
        self.ThisParse = ParseFormula(self.MainFrame)
        self.Gauge = ParseGauge(self.MainFrame, '解析进度')
        # 多线程
        pub.subscribe(self.GaugeUpdate, "GaugeUpdate")
        self.Threading_1 = threading.Thread(target=self.Parse, args=())
        self.Threading_1.start()
        self.GaugeFun()
        self.Threading_1.join()
        self.Save(expath)

    def Parse(self):
        for index, Sheet in enumerate(self.Book):
            for row, rowv in enumerate(Sheet):
                for col, cell in enumerate(rowv):
                    text = cell.value
                    text = self.ThisParse.StringParse(text)
                    if len(text) == 0:
                        Sheet.cell(row + 1, col + 1, '')
                    elif len(text) == 1:
                        Sheet.cell(row + 1, col + 1, text[0])
                    else:
                        Cell = Sheet.cell(row + 1, col + 1)
                        Font = Cell.font
                        Border = Cell.border
                        Align = Cell.alignment
                        for rowadd in range(len(text)):
                            cell = Sheet.cell(row + 1 + rowadd, col + 1, text[rowadd])
                            cell.font = copy.copy(Font)
                            cell.border = copy.copy(Border)
                            cell.alignment = copy.copy(Align)
            # 处理页眉页脚
            Data1 = ['oddFooter', 'oddHeader']
            Data2 = ['left', 'center', 'right']
            for i in Data1:
                for j in Data2:
                    text = getattr(getattr(getattr(Sheet, i), j), 'text')
                    text = self.ThisParse.StringParse(text)
                    if len(text) > 0:
                        text = text[0]
                    else:
                        text = ''
                    setattr(getattr(getattr(Sheet, i), j), 'text', str(text))
            
            pub.sendMessage("GaugeUpdate", value=index+1, text=Sheet.title)

    def GaugeFun(self):
        self.Gauge.SetRange(len(list(self.Book)))
        self.Gauge.ShowModal()
        self.Gauge.SetValue(0)
    
    def GaugeUpdate(self, value, text):
        self.Gauge.SetValue(value)
        self.Gauge.SetLabel(text)
        if value == len(list(self.Book)):
            self.Gauge.SetLabel('已完成解析请点击完成导出', 'all')

    def Save(self, path):
        self.Book.save(path)